package com.moleq.network;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/*
 * 
 * mutil conncet model
 */
public class ConnectHandler extends Thread {
	private ServerSocket sSocket = null;
	private int mMonitorPort = 6677;
	public boolean action = true;

	private CommunicationCallback mCommunicationCallback = null;

	public ConnectHandler(int port, CommunicationCallback callback) {
		mMonitorPort = port;
		mCommunicationCallback = callback;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();

		try {
			sSocket = new ServerSocket(mMonitorPort);
			System.out.println("connect handler socket started...");
			while (!sSocket.isClosed() && null != sSocket) {
				Socket socket = sSocket.accept();
				socket.setSoTimeout(5000);
				mCommunicationCallback.onConnected(socket.getInetAddress().getHostAddress());
			}
		} catch (Exception e) {
			e.printStackTrace();
			mCommunicationCallback.onError(e.getMessage());
		}
	}

	public void checkIpAddress(List<String> ips) {
		if (mCommunicationCallback != null) {
			mCommunicationCallback.onCheckNetworkStart();
		}

		if (ips != null && ips.size() > 0) {
			for (int i = 0; i < ips.size(); i++) {
				connect(ips.get(i));
			}
		}

		if (mCommunicationCallback != null) {
			mCommunicationCallback.onCheckNetworkComplete();
		}
	}
	
	public void connect(String ipAddress) {

		final String ip = ipAddress;
		Socket clientSocket = null;
		clientSocket = new Socket();
		try {
			InetSocketAddress isa;
			isa = new InetSocketAddress(ip, mMonitorPort);
			clientSocket.connect(isa, 1000);
			if (clientSocket.isConnected()) {
//				sleep(500);// sleep 1秒钟，等待对方处理完
				mCommunicationCallback.onConnected(ipAddress);
			}
		} catch (Exception e) {
			// e.printStackTrace();
			mCommunicationCallback.onDisconnected(e.getMessage());
		} finally {
			try {
				if (clientSocket != null) {
					clientSocket.close();
				}
			} catch (Exception e) {
				// e.printStackTrace();
				mCommunicationCallback.onError(e.getMessage());
			}
		}
	}

	public void release() {
		try {
			System.out.println("conncet handler socket closed ...");
			if (null != sSocket)
				sSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
